package com.cyh.core.framework.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import com.cyh.core.framework.common.constant.FileConstant;
import com.cyh.core.login.entity.User;
import com.cyh.core.login.repository.RoleRepository;
import com.cyh.core.login.repository.UsersRepository;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.Date;


public class JWTUtil {

    private final static String ymlPath= FileConstant.RESOURCE_PATH +"/application-dev.yml";

    /**
     * 创建JWT的Token
     * @param user
     * @param exTime
     * @return token
     */
    public static String CreateToken(User user, Integer exTime) {
        String token="";
        Date expiresDate = new Date(System.currentTimeMillis() + exTime.intValue()*60*1000);
        token= JWT.create().withAudience(user.getId().toString()).withSubject(user.getRoleid().toString())
                .withExpiresAt(expiresDate)
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }

    /**
     * 从token获取用户ID
     * @param token
     * @return ID
     */
    public static String GetIdFromToken(String token){
        String userId=null;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            return userId;
        } catch (JWTDecodeException j) {
            return null;
        }
    }

    /**
     * 从token获取用户ID
     * @param token
     * @return ID
     */
    public static String GetRidFromToken(String token){
        String rId=null;
        try {
            rId = JWT.decode(token).getSubject();
            return rId;
        } catch (JWTDecodeException j) {
            return null;
        }
    }

    /**
     * 验证JWT
     * @param token
     * @param password
     * @return 是否成功
     */
    public static boolean JWTVerify(String token,String password){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();
        try {
            jwtVerifier.verify(token);
            return true;
        }catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 从token获取当前用户
     * @param token
     * @return 当前用户
     */
    @Deprecated
    public static User GetUserFromToken(String token){
        UsersRepository repository= (UsersRepository) ApplicationContextUtil.getApplicationContext().getBean("usersRepository");
        RoleRepository roleRepository= (RoleRepository) ApplicationContextUtil.getApplicationContext().getBean("roleRepository");
/*
        Map<String,Object> map=null;
        try{
        YamlReader reader = new YamlReader(new FileReader(FileUtil.getRealPath(ymlPath)));
        map = reader.read(Map.class);
        }catch (Exception e){
            return null;
        }

        Integer id=Integer.parseInt(GetIdFromToken(token));
        DriverManagerDataSource dataSource= new DriverManagerDataSource();
        Map<String,Object> dataSourceMap=(Map<String, Object>) ((Map<String, Object>)map.get("spring")).get("datasource");
        dataSource.setDriverClassName(dataSourceMap.get("driver-class-name").toString());
        dataSource.setUrl(dataSourceMap.get("url").toString());
        dataSource.setUsername(dataSourceMap.get("username").toString());
        dataSource.setPassword(dataSourceMap.get("password").toString());
        JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);

 */
        //User user=jdbcTemplate.query("select * from user where id=?",new Object[] {id}, new BeanPropertyRowMapper<>(User.class)).get(0);
        Integer id=Integer.parseInt(GetIdFromToken(token));
        User user=repository.findById(id).get();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"  User From Repository "+user);
        user.setTempObject(roleRepository.findByRoleid(user.getRoleid()));
        return user;
    }

    /**
     * 从Http请求获取当前用户
     * @param httpServletRequest
     * @return 当前用户
     */
    @Deprecated
    public static User GetUserFromToken(HttpServletRequest httpServletRequest){
        Cookie[]cookies= httpServletRequest.getCookies();
        String token=null;
        if(cookies!=null) {
            for (Cookie coo : cookies) {
                if (coo.getName().equals("token")) {
                    token=coo.getValue();
                    break;
                }
            }
        }
        else return null;
        if(token==null)return null;
        return GetUserFromToken(token);
    }

    public static User GetUserFromToken(){
        UserTokenUtil userTokenUtil= (UserTokenUtil) ApplicationContextUtil.getApplicationContext().getBean("userTokenUtil");
        return userTokenUtil.getCurrentUser();
    }

    public static String getTokenFromHTTP(HttpServletRequest httpServletRequest){
        Cookie []cookies= httpServletRequest.getCookies();
        String token=null;
        if(cookies!=null) {
            for (Cookie coo : cookies) {
                if (coo.getName().equals("token")) {
                    return coo.getValue();
                }
            }
        }
        return null;
    }
}
